// pages/activityAsk/activityAsk.js
import {
    activityReleaseactivity,
    jobAll
} from "../../services/activityReq";
import {
    isNumber
} from "../../miniprogram_npm/@vant/weapp/common/validator";
const moment = require("../../utils/moment");
let QQMapWX = require('../../utils/qqmap-wx-jssdk.min');
let qqmapsdk;

function formatTime(time) {
    return moment(time).format("YYYY-MM-DD hh:mm:ss")
}

Page({

    /**
     * 页面的初始数据
     */
    data: {
        isLogin: false,
        EditorTimeShow: false,
        EditorEndTimeShow: false,
        address: '',
        EditorJob: false,
        jobList: [{
            jobId: '',
            jobName: '',
            jobNumber: 1,
            jobScore: 1,
        }],
        columns: [],
        fileList: [],
        jobAllList: [],
        multiIndex: [0, 0, 0],
        EditorJobShow: false,
        tmpJob: {
            jobId: '',
            jobName: '',
            jobNumber: 1,
            jobScore: 1,
        },
        StartTime: formatTime(new Date().getTime()),
        EndTime: formatTime(new Date().getTime()),
        currentTime:new Date().getTime(),
        Form: {
            StartTime: new Date().getTime(),
            EndTime: new Date().getTime()
        },
        tmpIndex: null,
        // volunteerMobile: '',
        // volunteerName: '',
        activityDisc: '',
        activityName: '',
        type: '',
        charge: null
    },

    /**
     * 生命周期函数--监听页面加载
     */
    handleSelectCharge(event) {

    },
    handleSelectIsFree(event) {

    },

    handleChangeValue(event) {
        let {target} = event.currentTarget.dataset;

        let value = event.detail;
        if (target) {
            if (target === "charge" && !isNumber(value)) return wx.showToast({
                title: "请输入数字",
                icon: "error"
            })
            this.setData({
                [target]: value
            })
        }
    },

    handleReleaseActivity() {
        let token = wx.getStorageSync('token');
        let address = this.data.address;
        let f = this.data.Form;
        let activityName = this.data.activityName;
        let activityDisc = this.data.activityDisc;
        let jobList = this.data.jobList;
        let type = this.data.type;
        let charge = this.data.charge;
        let tmp = 0;

        jobList.splice(0, 1);

        for (let i of jobList) {
            tmp += ~~(i.jobNumber)
        }
        if (!address.address) {
            return wx.showToast({
                title: '未填写活动地址',
                icon: "error"
            });
        }

        if (!activityName) return wx.showToast({
            title: '未填写活动名称',
            icon: "error"
        });
        if (!type) return wx.showToast({
            title: '未填写类型',
            icon: "error"
        });
        let fileList = this.data.fileList;
        if (!fileList[0].url) return wx.showToast({
            title: '未上传活动图片',
            icon: "error"
        });
        if (!type) return wx.showToast({
            title: '未填写类型',
            icon: "error"
        });
        if (!activityDisc) return wx.showToast({
            title: '未填写活动描述',
            icon: "error"
        });
        if (isNaN(~~charge)) return wx.showToast({
            title: "费用请输入数字"
        })

        if (!jobList) return wx.showToast({
            title: "请设置岗位",
            icon: "error"
        })

        if (!tmp) return wx.showToast({
            title: "请设置岗位",
            icon: "error"
        })

        wx.uploadFile({
            url: 'https://www.16tongxing.net/upload/files',
            filePath: fileList[0].url,
            header: {
                'Authorization': token
            },
            name: 'files',
            success(res) {
                let params = {
                    activityEntity: {
                        activityAddress: JSON.stringify(address),
                        activityDatetime: f.StartTime,
                        activityDisc: activityDisc,
                        activityEndDatetime: f.EndTime,
                        activityIsfree: ~~!!!charge,
                        serveTime: `${formatTime(f.StartTime)},${formatTime(f.EndTime)}`,
                        activityMoney: 0,
                        activityName: activityName,
                        activityRecruitPeople: tmp,
                        community: '',
                        imagePath: fileList[0].url,
                        activityType: type
                    },
                    jobs: jobList
                }
                activityReleaseactivity(params, res => {
                    console.log(res)
                    if (!res.data.code) {
                        return wx.showToast({
                            title: '发布成功',
                            duration: 1000,
                            mask: true,
                            success() {
                                setTimeout(() => wx.redirectTo({
                                    url: './activityAsk',
                                }), 1000)
                            }
                        })
                    }

                })
            },
            fail(res) {
                return wx.showToast({
                    title: '图片上传失败啦',
                    icon: "error"
                })
            }
        });
    },
    onLoad: function (options) {
        qqmapsdk = new QQMapWX({
            key: '5FABZ-HSL6W-ICGRY-RDQFJ-WD6PK-Y6B2P'
        });
        let address = this.data.address
        let selectAddress = wx.getStorageSync('selectAddress');
        if (selectAddress) {
            address = selectAddress
            this.setData({
                address
            })
            wx.removeStorage({
                key: 'selectAddress',
            })
        }
        this.handleGetJobList()
    },
    moveToLocation() {
        let address = this.data.address;
        wx.chooseLocation({
            success: function (res) {
                address = {
                    address: res.address,
                    lng: res.longitude,
                    lat: res.latitude
                }
                wx.setStorageSync('selectAddress', address)
                wx.redirectTo({
                    url: './activityAsk',
                })
            },
            fail: function (err) {
                console.log(err)
            }
        });

    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        // 判断是否登录
        if (wx.getStorageSync('token')) {
            this.setData({
                isLogin: true
            })
        } else {
            // 尚未登陆 提示跳转
            wx.reLaunch({
                url: '../login/login',
            })
        }

    },
    onInput(event) {
        this.setData({
            currentDate: event.detail,
        });
    },
    onClose() {
        this.setData({
            EditorTimeShow: false,
            EditorEndTimeShow: false,
            EditorJobShow: false
        })
    },
    handleConfirmEndTime(e) {
        let Form = this.data.Form;
        Form["EndTime"] = e.detail
        this.setData({
            EditorTimeShow: false,
            EditorEndTimeShow: false,
            EditorJobShow: false,
            EndTime: formatTime(e.detail),
            Form

        })

    },
    handleConfirmStartTime(e) {
        let Form = this.data.Form;
        Form["StartTime"] = e.detail
        this.setData({
            EditorTimeShow: false,
            EditorEndTimeShow: false,
            EditorJobShow: false,
            StartTime: formatTime(e.detail),
            Form
        })

    },
    onChange() {},
    handleSelectJobChange({
        detail
    }) {
        const {
            index,
            value
        } = detail
        let tmpJob = this.data.tmpJob;
        let jobAllList = this.data.jobAllList;

        tmpJob["jobName"] = value;
        tmpJob["jobId"] = jobAllList[index].jobId;
        this.setData({
            tmpJob
        })
    },
    handleSelectNumber(event) {
        let tmpJob = this.data.tmpJob;
        tmpJob["jobNumber"] = event.detail
        this.setData({
            tmpJob
        })
    },
    handleSelectScore(event) {
        let tmpJob = this.data.tmpJob;
        tmpJob["jobScore"] = event.detail;
        this.setData({
            tmpJob
        })
    },
    handleConfirmJob() {

        let jobList = this.data.jobList;
        let tmpJob = this.data.tmpJob;
        this.setData({
            EditorJobShow: false
        })
        jobList.push(
            JSON.parse(JSON.stringify(tmpJob))
        )
        this.setData({
            jobList
        })
    },
    handleSelectStartTiem() {
        this.setData({
            EditorTimeShow: true
        })
    },
    handleSelectEndTiem() {
        this.setData({
            EditorEndTimeShow: true
        })
    },
    handleGetJobList() {
        jobAll(res => {
            let tmp = res.data.data.map(
                val => val.jobName
            )
            this.setData({
                jobAllList: res.data.data,
                columns: tmp
            })


        })
    },
    handleDelete() {
        let fileList = this.data.fileList;
        fileList = []
        this.setData({
            fileList
        })
    },
    handleToDelJob(e) {
        console.log(e)
        const index = ~~e.currentTarget.dataset.index;
        console.log(index)
        let jobList = this.data.jobList;
        console.log(jobList)
        jobList.splice(index, 1)
        this.setData({
            jobList
        })
    },
    handleToAddJob({
        currentTarget
    }) {
        let {
            index
        } = currentTarget.dataset;
        let tmpIndex = this.data.tmpIndex;
        tmpIndex = index;
        this.setData({
            tmpIndex,
            EditorJobShow: true
        })
    },

    afterRead(event) {
        const {
            file
        } = event.detail;
        console.log(file)
        let self = this;
        // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
        // console.log(token)
        let fileList = [];
        fileList.push({
            ...file,
            url: file.url
        });
        self.setData({
            fileList
        });

    },
    handleSelectJob() {
        this.setData({
            EditorJob: true,
        })
    },
})
